package com.github.florent37.materialimageloading;

import ohos.agp.animation.AnimatorProperty;
import ohos.agp.animation.AnimatorValue;
import ohos.agp.components.Image;
import ohos.agp.components.element.Element;
import ohos.agp.render.ColorMatrix;

public class MaterialImageLoading {

    private static final int DEFAULT_DURATION = 3000;
    final Image imageView;
    final Element drawable;
    int duration = DEFAULT_DURATION;
    float saturation;
    AnimatorValue animationSaturation;
    AnimatorValue animationContrast;
    AnimatorProperty animationAlpha;

    private MaterialImageLoading(Image imageView) {
        this.imageView = imageView;
        this.drawable = imageView.getImageElement();
    }

    public static MaterialImageLoading animate(Image imageView) {
        return new MaterialImageLoading(imageView);
    }

    public int getDuration() {
        return duration;
    }

    public MaterialImageLoading setDuration(int duration) {
        this.duration = duration;
        return this;
    }

    public void start() {
        setup(duration);

        animationSaturation.start();
        animationContrast.start();
        animationAlpha.start();
    }

    public void cancel() {
        animationSaturation.cancel();
        animationContrast.cancel();
        animationAlpha.cancel();
    }

    private ColorMatrix setContrast(float contrast) {
        float scale = contrast + 1.f;
        float translate = (-.5f * scale + .5f) * 255.f;
        float[] array = new float[]{
                scale, 0, 0, 0, translate,
                0, scale, 0, 0, translate,
                0, 0, scale, 0, translate,
                0, 0, 0, 1, 0};
        return new ColorMatrix(array);
    }

    private void setup(int duration) {
        imageView.setAlpha(0);
        //region saturation
        animationSaturation = new AnimatorValue();
        animationSaturation.setLoopedCount(1);
        animationSaturation.setDuration(duration);
        animationSaturation.setValueUpdateListener((animatorValue, value) -> {
           saturation = 0.2f + value / 0.8f;
        });
        //endregion

        //region contrast
        animationContrast =  new AnimatorValue();
        animationContrast.setLoopedCount(1);
        animationContrast.setDuration((long) (duration * 3f / 4f));
        animationContrast.setValueUpdateListener((animatorValue, value) -> {
                ColorMatrix colorMatrix = setContrast(value);
                colorMatrix.setSaturation(saturation);
                drawable.setColorMatrix(colorMatrix);
        });
        //endregion

        //region alpha
//        animationAlpha = ObjectAnimator.ofFloat(imageView, View.ALPHA, 0f, 1f);
        animationAlpha = new AnimatorProperty();
        animationAlpha.setTarget(imageView);
        animationAlpha.alpha(1);
        animationAlpha.setDuration((long) (duration / 2f));
        //endregion
    }

}